// pages/meiwen/meiwen.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formats:{},
    placeholder:'开始输入...',
    editorHeight:300,
    keyboardHeight:0,
    isIOS:false
  },

  //页面加载，生命周期函数
  onLoad(){
    const platform=wx.getDeviceInfo().platform
    const isIOS=platform==='ios'
    this.setData({isIOS})
    const that=this
    this.updatePosition(0)
    let keyboardHeight=0
    wx.onKeyboardHeightChange((res) => {
      if(res.height===keyboardHeight) return
      const duration=res.height>0 ? res.duration*1000:0
      keyboardHeight=res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop:0,
          success(){
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      },duration)
    })
  },

  //更新编辑框高度和键盘高度
  updatePosition(keyboardHeight){
    const toolbarHeight=50
    const windowHeight=wx.getWindowInfo().windowHeight
    const platform=wx.getDeviceInfo().platform
    let editorHeight=keyboardHeight>0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({editorHeight,keyboardHeight})
  },

  //编辑准备
  onEditorReady(){
    const that=this
    wx.createSelectorQuery().select('#editor').context(function(res){
      that.editorCtx=res.context
    }).exec()
  },

  //编辑样式
  format(e){
    let {name,value}=e.target.dataset
    if(!name) return
    this.editorCtx.format(name,value)
  },

  //改变状态条
  onStatuschange(e){
    const formats=e.detail
    this.setData({formats})
    console.log(formats)
  },

  //清除输入内容
  clear(){
    this.editorCtx.clear({
      success:function(res){
        console.log("clear success")
      }
    })
  },

  //清除格式
  removeFormat(){
    this.editorCtx.removeFormat()
  },

  //插入日期
  insertDate(){
    const date=new Date()
    const formatDate=`${date.getFullYear()}/${date.getMonth()+1}/${date.getDate()}`
    this.editorCtx.insertText({
      text:formatDate
    })
  },

  //插入图片
  insertImage() {
    const that = this;

    wx.chooseMedia({
      count: 1,  // 只能选择1个文件
      mediaType: ['image'],  // 只允许选择图片
      sourceType: ['album', 'camera'],  // 可从相册或相机选择
      sizeType: ['compressed'],  // 压缩图片
      success(res) {
        // 检查是否有选中文件
        if (res.tempFiles && res.tempFiles.length > 0) {
          const tempFilePath = res.tempFiles[0].tempFilePath;

          // 显示加载中状态
          wx.showLoading({
            title: '正在插入图片...',
            mask: true
          });

          that.editorCtx.insertImage({
            src: tempFilePath,
            data: {
              id: Date.now().toString(),  // 生成唯一ID
              type: 'user-upload'
            },
            width: '80%',
            success() {
              wx.showToast({
                title: '图片插入成功',
                icon:'success'
              });
            },
            fail(err) {
              console.error('图片插入失败:', err);
              wx.showToast({
                title: '图片插入失败',
                icon: 'none'
              });
            },
            complete() {
              wx.hideLoading();
            }
          })
        }
      },
      fail(err) {
        console.error('选择媒体失败:', err);
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  },

  //跳转到首页
  toHomepage(){
    wx.switchTab({
      url: '../homepage/homepage',
    })
    
  }
})
